package com.example.demo.leetcode;

/**
 * 链表：<a href="https://leetcode.cn/problems/rotate-list/">https://leetcode.cn/problems/rotate-list/</a>
 */
public class _61_旋转链表 {
    public static void main(String[] args) {

        ListNode node = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));

        ListNode node2 = new ListNode(1, new ListNode(2));
        ListNode node1 = rotateRight(node2, 1);
        System.out.println(node1);
    }

    /**
     * 先断开，在连接。
     *
     * @param head
     * @param k
     * @return
     */
    public static ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) {
            return head;
        }

        int n = 1;
        ListNode tail = head;
        while (tail.next != null) {
            tail = tail.next;
            n++;
        }

        k = k % n;
        if (k == 0) {
            return head;
        }

        k = n - k - 1;

        ListNode current = head;
        int i = 0;
        while (i < k) {
            current = current.next;
            i++;
        }

        ListNode pre = current.next;
        current.next = null;

        tail.next = head;
        return pre;
    }


    /**
     * 先连接成环，在断开。
     *
     * @param head
     * @param k
     * @return
     */
    public ListNode rotateRight1(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null) {
            return head;
        }
        int n = 1;
        ListNode iter = head;
        while (iter.next != null) {
            iter = iter.next;
            n++;
        }
        int add = n - k % n;
        if (add == n) {
            return head;
        }
        iter.next = head;
        while (add-- > 0) {
            iter = iter.next;
        }
        ListNode ret = iter.next;
        iter.next = null;
        return ret;
    }
}
